package com.huluobo.a2203monthdemo.news

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2203monthdemo.R
import com.huluobo.a2203monthdemo.aapter.NewsAdapter
import com.huluobo.a2203monthdemo.databinding.ActivityNewsBinding
import com.huluobo.base.bean.NewsBean
import com.huluobo.base.mvvm.BaseActivity
import com.huluobo.base.net.Const
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

@AndroidEntryPoint
class NewsActivity : BaseActivity<ActivityNewsBinding, NewsViewModel>() {
    private lateinit var newsAdapter: NewsAdapter
    private var page = 0
    override fun initData() {
        val map = mutableMapOf<String, Int>()
        map[Const.PARAM_PAGE] = page
        val json = Gson().toJson(map)
        val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
        viewModel.getAllNews(body)

        viewModel.getNewsSuccess.observe(this) {
            val list = Gson().fromJson(it, NewsBean::class.java)
            newsAdapter.data.clear()
            newsAdapter.data.addAll(list)
            newsAdapter.notifyDataSetChanged()
        }
    }

    override fun initView() {
        binding.newsHeader.headerBack.setOnClickListener { finish() }
        binding.newsHeader.headerTitle.text = "新闻"
        binding.newsHeader.headerAdd.visibility = View.VISIBLE
        binding.newsHeader.headerAdd.setOnClickListener {
            val intent = Intent(this, AddNewsActivity::class.java)
            startActivity(intent)
        }
        binding.newsRv.layoutManager = LinearLayoutManager(this)
        newsAdapter = NewsAdapter()
        binding.newsRv.adapter = newsAdapter
        binding.newsPageTv.text = "第${page + 1}页"


        binding.newsPrePage.setOnClickListener {
            if (page != 0) {
                page--
                val map = mutableMapOf<String, Int>()
                map[Const.PARAM_PAGE] = page
                val json = Gson().toJson(map)
                val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
                viewModel.getAllNews(body)
                binding.newsPageTv.text = "第${page + 1}页"
            } else {
                ToastUtils.showLong("已经是第一页了")
            }
        }

        binding.newsPostPage.setOnClickListener {
            page++
            val map = mutableMapOf<String, Int>()
            map[Const.PARAM_PAGE] = page
            val json = Gson().toJson(map)
            val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
            viewModel.getAllNews(body)
            binding.newsPageTv.text = "第${page + 1}页"
        }
    }
}